<?php

namespace app\admin\controller\wx;

use app\admin\model\agent\Info;
use app\common\controller\Backend;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use PHPExcel;
use PHPExcel_IOFactory;
use PHPExcel_Shared_Date;
use PHPExcel_Style;
use PHPExcel_Style_Alignment;
use PHPExcel_Style_Border;
use PHPExcel_Style_Fill;
use PHPExcel_Style_NumberFormat;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Wximportlog extends Backend
{
    
    /**
     * Wximportlog模型对象
     * @var \app\admin\model\Wximportlog
     */
    protected $model = null;
    protected $modelOrder = null;
    protected $modelPro = null;
    protected $modelProduct = null;
    protected $modelOrderInfo = null;
    protected $searchFields = 'id,info.agent_name';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Wximportlog;
        $this->modelOrder = new \app\admin\model\Wxorder;
        $this->modelOrderInfo = new \app\admin\model\Wxorderinfo;

        $this->modelPro = new \app\admin\model\Wxpro;
        $this->modelProduct = new \app\admin\model\Wxproduct;
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->with(['info'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->with(['info'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                $row->getRelation('info')->visible(['agent_name']);
            }
            $list = collection($list)->toArray();
            foreach ($list as &$item)
            {
                //通过/未通过/未审核/已修改待审核/申请作废/已作废
                $result = $this->modelOrder->where('id','in',$item['order_ids'])->field('state,count(state) as num')->group('state')->select();//通过
                $result = array_column($result,'num','state');
                $state = isset($result[1]) ? '通过('.$result[1].'),' : '通过(0),';
                $state .= isset($result[0]) ? '未审核('.$result[0].'),' : '未审核(0),';//未审核
                $state .= isset($result[2]) ? '未通过('.$result[2].'),' : '未通过(0),';//未通过
                $state .= isset($result[3]) ? '已修改/待审核('.$result[3].'),' : '已修改/待审核(0),';//已修改/待审核
                $state .= isset($result[8]) ? '申请作废('.$result[8].'),' : '申请作废(0),';//申请作废
                $state .= isset($result[9]) ? '已作废('.$result[9].')' : '已作废(0)';//已作废
                $state .= isset($result[10]) ? '申请退货('.$result[10].')' : '申请退货(0)';//已作废
                $state .= isset($result[11]) ? '退货成功('.$result[11].')' : '退货成功(0)';//已作废
                $weifa = $this->modelOrder->where('id','in',$item['order_ids'])->where('courierBut','=',' ')->count();//统计快递
                $yifa = $this->modelOrder->where('id','in',$item['order_ids'])->where('courierBut','<>',' ')->count();//统计快递
                $item['check'] = $state;
                $item['courierBut'] = "已发货($yifa),"."未发货($weifa)";
                $item['dc'] = 0;
                if( (isset($result[8]) && $result[8] > 0) ||
                    (isset($result[0]) && $result[0] > 0) ||
                    (isset($result[2]) && $result[2] > 0) ||
                    (isset($result[3]) && $result[3] > 0) ||
                    (isset($result[10]) && $result[10] > 0) ||
                    (!isset($result[1])) ) {
                    $item['dc'] = 1;
                }

            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    public function cwexport($ids = null)
    {
        $createtime = date('Y-m-d H:i:s',time());
        $orderList = $this->getList($ids);
        //查询半成品数据
        $orderList =  $this->pro($orderList);
        $excel = new PHPExcel();

        $excel->getProperties()
            ->setCreator("YangLiu")
            ->setLastModifiedBy("YangLiu")
            ->setTitle("销售订单")
            ->setSubject("Subject");
        $excel->getDefaultStyle()->getFont()->setName('Microsoft Yahei');
        $excel->getDefaultStyle()->getFont()->setSize(12);

        $this->sharedStyle = new PHPExcel_Style();
        $this->sharedStyle->applyFromArray(
            array(
                'fill'      => array(
                    'type'  => PHPExcel_Style_Fill::FILL_SOLID,
                    'color' => array('rgb' => '000000')
                ),
                'font'      => array(
                    'color' => array('rgb' => "000000"),
                ),
                'alignment' => array(
                    'vertical'   => PHPExcel_Style_Alignment::VERTICAL_CENTER,
                    'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
                    'indent'     => 1
                ),
                'borders'   => array(
                    'allborders' => array('style' => PHPExcel_Style_Border::BORDER_THIN),
                )
            ));

        $worksheet = $excel->setActiveSheetIndex(0);
        $worksheet->setTitle('标题');

        $worksheet->setCellValue("A1", "单据日期");
        $worksheet->setCellValue("B1", "单据编号");
        $worksheet->setCellValue("C1", "业务类型编码");
        $worksheet->setCellValue("D1", "业务类型");
        $worksheet->setCellValue("E1", "售后类型");
        $worksheet->setCellValue("F1", "客户编码");
        $worksheet->setCellValue("G1", "客户");
        $worksheet->setCellValue("H1", "结算客户编码");
        $worksheet->setCellValue("I1", "结算客户");
        $worksheet->setCellValue("J1", "部门编码");
        $worksheet->setCellValue("K1", "部门");
        $worksheet->setCellValue("L1", "业务员编码");
        $worksheet->setCellValue("M1", "业务员");
        $worksheet->setCellValue("N1", "运输方式");
        $worksheet->setCellValue("O1", "送货地址");
        $worksheet->setCellValue("P1", "联系人");
        $worksheet->setCellValue("Q1", "联系电话");
        $worksheet->setCellValue("R1", "客户手机号");
        $worksheet->setCellValue("S1", "合同号");
        $worksheet->setCellValue("T1", "收款方式");
        $worksheet->setCellValue("U1", "外部单据号");
        $worksheet->setCellValue("V1", "按仓库拆单出库");
        $worksheet->setCellValue("W1", "备货周次");
        $worksheet->setCellValue("X1", "收货方姓名");
        $worksheet->setCellValue("Y1", "收货方电话");
        $worksheet->setCellValue("Z1", "收货方地址");
        $worksheet->setCellValue("AA1", "收货方式");
        $worksheet->setCellValue("AB1", "周次");
        $worksheet->setCellValue("AC1", "场次");
        $worksheet->setCellValue("AD1", "终端客户");
        $worksheet->setCellValue("AE1", "备注");
        $worksheet->setCellValue("AF1", "仓库编码");
        $worksheet->setCellValue("AG1", "仓库");
        $worksheet->setCellValue("AH1", "项目编码");
        $worksheet->setCellValue("AI1", "项目");
        $worksheet->setCellValue("AJ1", "客户存货名称");
        $worksheet->setCellValue("AK1", "客户存货编码");
        $worksheet->setCellValue("AL1", "存货编码");
        $worksheet->setCellValue("AM1", "存货名称");
        $worksheet->setCellValue("AN1", "适用BOM");
        $worksheet->setCellValue("AO1", "销售单位");
        $worksheet->setCellValue("AP1", "数量");
        $worksheet->setCellValue("AQ1", "报价");
        $worksheet->setCellValue("AR1", "折扣%");
        $worksheet->setCellValue("AS1", "税率");
        $worksheet->setCellValue("AT1", "含税单价");
        $worksheet->setCellValue("AU1", "含税金额");
        $worksheet->setCellValue("AV1", "财务备注");
        $orderTotal = [];
        array_walk($orderList,function ($value,$k) use ($worksheet,&$orderTotal){
            $orderTotal[] = $value['order_sn'];
            /**
             *  数量* 码洋 = 报价
             *  （没折扣）订单总价 *  取码洋总价  = 比例 ）    （每一类商品总价 * 折扣 = 含税金额）
             *  (取折扣)码洋 * 折扣 = 含税金额
             */
            $Key = $k+2;
            $date = date('Y/m/d',$value['xdtime']);
            $worksheet->setCellValue("A".$Key, $date);//下单日期
            $worksheet->setCellValue("B".$Key, ' '.$value['order_sn'].' ');//订单号
            $worksheet->setCellValue("C".$Key, 15);//默认15
            $worksheet->setCellValue("F".$Key, ' '.$value['finance_code'].' ');//客户对应财务的编码

            $worksheet->setCellValue("X".$Key, $value['name']);//收货人名称
            $worksheet->setCellValue("Y".$Key, $value['phone']);//收货人电话
            $worksheet->setCellValue("Z".$Key, $value['address']);//收货人地址
            $worksheet->setCellValue("AL".$Key, ' '.$value['code'].' ');//存货编码
            $worksheet->setCellValue("AF".$Key, '0233');//存货编码
            $worksheet->setCellValue("AE".$Key, $value['import_note']);//备注
            $worksheet->setCellValue("AM".$Key, $value['pro_name']);//存货名称
            $worksheet->setCellValue("AP".$Key, $value['num']);//数量
            $worksheet->setCellValue("AQ".$Key, $value['ministrial']);//码洋
            $sui = $value['tax'] * $value['num'];
            if($value['lts'] == 0)
            {
                $sui = $value['ministrial'] * $value['num'];
            }
            $zhekou = number_format(($value['lts'] * 100),2);
            $worksheet->setCellValue("AR".$Key, $zhekou."%");//折扣
            $worksheet->setCellValue("AU".$Key, $sui);//含税金额
            $worksheet->getColumnDimension('A')->setWidth(15); //设置列宽
            $worksheet->getColumnDimension('B')->setWidth(30); //设置列宽
            $worksheet->getColumnDimension('C')->setWidth(10); //设置列宽
            $worksheet->getColumnDimension('F')->setWidth(15); //设置列宽
            $worksheet->getColumnDimension('Y')->setWidth(15); //设置列宽
            $worksheet->getColumnDimension('Z')->setWidth(35); //设置列宽
            $worksheet->getColumnDimension('AL')->setWidth(15); //设置列宽
            $worksheet->getColumnDimension('AM')->setWidth(20); //设置列宽
        });
        //print_r(count(array_flip($orderTotal)));exit;
        $keys =count($orderList)+3;
        $worksheet->setCellValue("A".$keys, '订单合计');//
        $worksheet->setCellValue("B".$keys, count(array_flip($orderTotal)));
        unset($list);
        $excel->createSheet();
        $endtime = date('Y-m-d H:i:s',time());
        $title = '财务导出'.date("YmdHis");
        if(count(explode(',',$ids)) == 1)
        {
            $row = $this->model->get($ids);
            $row->cw += 1;
            $row->save();
            $agentName = Info::getName($row->agent_id);
            $title = '财务-'.$agentName.'-'.$row->id.'-'.date('Y-m-d').'-导出次数'.$row->wl;
            \app\admin\model\Wxorder::msg([
                'moban'=>'cwdc',
                'num'=>$row->cw,
                'id'=>$row->id,
                'createtime'=>$createtime,
                'endtime'=>$endtime,
                'name'=>$this->auth->username
            ]);

        }else{
        foreach (explode(',',$ids) as $value)
        {
            $row = $this->model->get($value);
            $row->cw += 1;
            $row->save();
                \app\admin\model\Wxorder::msg([
                    'moban'=>'cwdc',
                    'num'=>$row->cw,
                    'id'=>$row->id,
                    'createtime'=>$createtime,
                    'endtime'=>$endtime,
                    'name'=>$this->auth->username
                ]);
            }
        }

        unset($createtime,$endtime);
        // Redirect output to a client’s web browser (Excel2007)

        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $title . '.xlsx"');
        header('Cache-Control: max-age=0');
        // If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');

        // If you're serving to IE over SSL, then the following may be needed
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0

        $objWriter = PHPExcel_IOFactory::createWriter($excel, 'Excel2007');
        $objWriter->save('php://output');
        $row->save();
        return;
    }

    protected function getList($ids)
    {
        $orderList = [];
        try {

            $list = collect($this->model->where('id', 'in', $ids)->select())->toArray();
            $orderList = [];
            foreach ($list as $item)
            {
                /**
                 * B表的 单据日期  单据编号  金额
                C表的 客户编号
                B表的 姓名 电话 地址
                D表的 存货编码  码洋
                A表的  数量
                业务类型编码15
                 */
                $result = collection($this->modelOrderInfo
                    ->alias('a')
                    ->join('hdyj_wxorder b','a.order_sn = b.order_sn')
                    ->join('hdyj_agent_info c','b.agent_id = c.id')
                    ->where('b.id','in',$item['order_ids'])
                    ->where('b.state = 1')//审核通过的
                    ->field('b.id,c.agent_name,a.wxproduct_id,c.id as agent_id,b.deliveryForm,b.import_note,b.weigh as weigh,a.num as num,b.akg,a.lts as lts,a.tax as tax,b.receipt as name,b.phone as phone,b.address as address,b.xdtime as xdtime,b.order_sn as order_sn,b.amount,c.finance_code as finance_code,c.discount_array as discount_array')
                    ->select())->toArray();
                foreach ($result as &$items) {
                    $row = $this->modelProduct->get($items['wxproduct_id']);
                    $items['type'] = $row->type;
                    $items['unit'] = $row->unit;
                    $items['ministrial'] = $row->ministrial;
                    $items['wxpro_ids'] = $row->wxpro_ids;
                    unset($items['wxproduct_id']);
                }
                $orderList = array_merge($orderList,$result);
            }
        } catch (DataNotFoundException $e) {
            $this->error($e->getMessage());
        } catch (ModelNotFoundException $e) {
            $this->error($e->getMessage());
        } catch (DbException $e) {
            $this->error($e->getMessage());
        }
        return $orderList;
    }

    //财务查询半成品
    protected function pro(array $orderLsit)
    {
        $orderimport = [];
        foreach ($orderLsit as $item)
        {
            $data = collection($this->modelPro->where('id','in',$item['wxpro_ids'])->field('code,type,name,ministrial,fenlei,kemu,banben')->select())->toArray();
            unset($item['wxpro_ids']);
            foreach ($data as $val)
            {
                if(!$ministrial = $this->modelProduct->get(['name'=>$val['name']]))
                {
                    $item['ministrial'] = $val['ministrial'];
                }else{
                    $item['ministrial'] = $ministrial->ministrial;
                }
                if($item['lts'] < 1)
                {
                    $item['tax'] = $item['ministrial'] * $item['lts'];
                }else{
                    //（没折扣）订单总价 / 取所有商品码洋总价  = 比例 ）    （每一类商品总价 * 折扣 = 含税金额）
                    $mayang = $this->modelOrderInfo->where('order_sn',$item['order_sn'])->sum('price');
                    $item['lts'] = $item['amount'] / $mayang;
                    $item['tax'] = $item['lts'] * $item['ministrial'];
                }

                $item['code'] = $val['code'];
                $item['pro_name'] = $val['name'];

                $orderimport[] = $item;
            }
        }
        return $orderimport;
    }

    /**
     * 取出半成品 合并订单
     * @param array $list
     * @return array
     */
    protected function wlPro(array $list)
    {
        $data = [];
        foreach ($list as $item)
        {
            unset($item['lts'],$item['tax'],$item['type'],$item['unit'],$item['discount_array']);
            $pro = collection($this->modelPro->where('id','in',$item['wxpro_ids'])->select())->toArray();
            $proData = [];
            if($item['num'] > 1)
            {
                for ($i=1;$i<=$item['num'];$i++)
                {
                    $proData[$i] = $pro;
                }
                $proData = array_merge(...$proData);
            }else{
                $proData = $pro;
            }
            $item['pro'] = $proData;
            $data[md5($item['name'].$item['phone'].$item['address'])][] = $item;
        }

        $dataArr = [];
        foreach ($data as &$val)
        {
            $sum = array_sum(array_column($val, 'akg'));
            $array = [];
            foreach ($val as $v)
            {
                if(!$array)
                {
                    $array = $v;
                }else{
                    $array['order_sn'] .=','.$v['order_sn'];
                    $array['pro'] = array_merge($array['pro'],$v['pro']);
                }
            }
            $array['akg'] = $sum;
            $dataArr[] = $array;
        }

        return $dataArr;
    }

    /**
     * 物流
     * @param array $list
     * @return array
     */
    protected function wlOrder(array $list)
    {
        $arr = [];
        foreach ($list as $key=>$item)
        {
            //北京的订单合并不管重量
            if(strpos($item['address'],'北京') !== false){
                unset($item['wxpro_ids']);
                $item['address'] = trim($item['address']);
                $item['pro'] = $this->getNum($item['pro']);
                $item['status'] = 1;
                $arr[] = $item;
            }else{
                $order_sn = explode(',',$item['order_sn']);
                $order_sn = implode(',',array_values(array_unique($order_sn)));
                $TxPro = $this->txsf($item['pro']);

                foreach ($TxPro as $key=>$value)
                {
                    $sum = array_sum(array_column($value, 'kg'));
                    $value = $this->getNum($value);
                    $arr[] = [
                        'agent_name'=>$item['agent_name'],
                        'agent_id'=>$item['agent_id'],
                        'akg'=>$sum,
                        'name'=>$item['name'],
                        'phone'=>$item['phone'],
                        'address'=>trim($item['address']),
                        'ministrial'=>$item['ministrial'],
                        'xdtime'=>$item['xdtime'],
                        'deliveryForm'=>$item['deliveryForm'],
                        'weigh'=>$item['weigh'],
                        'import_note'=>$item['import_note'],
                        'order_sn'=>$order_sn,
                        'amount'=>$item['amount'],
                        'finance_code'=>$item['finance_code'],
                        'status'=>2,
                        'pro'=>$value
                    ];
                }
            }
        }
        return $arr;
    }

    /**
     * 获取数组重复的数据
     * @param $arr
     * @param $key
     * @return array
     */
    protected function getNum($arr, $key='id')
    {
        $arrNum = array_count_values(array_column($arr, $key));
        $data = [];
        foreach ($arr as $item)
        {
            if($arrNum[$item['id']] > 1)
            {
                $item['num'] = $arrNum[$item['id']];
                $data[$item['id']] = $item;
            }else{
                $item['num'] = 1;
                $data[$item['id']] = $item;
            }
        }
        return $data;
    }

    /**
     * 贪心算法
     * @param array $items
     * @return array
     */
    protected function  txsf($items = [])
    {
        $source_array = $items;
        $transfer_array = array();
        while (count($source_array) > 0) {
            $max = array_shift($source_array);
            if ($max['kg'] >= 3.65) {
                array_push($transfer_array, array($max));
            } else {
                $temp = array($max);
                foreach ($source_array as $k => $v) {
                    $sum = array_sum(array_column($temp, 'kg'));
                    if (($sum + $v['kg']) <= 3.65) {
                        array_push($temp, $v);
                        unset($source_array[$k]);
                    }
                }
                array_push($transfer_array, $temp);
            }
        }
        return $transfer_array;
    }

    public function wlexport($ids = null)
    {
        $createtime = date('Y-m-d H:i:s',time());
        $list = $this->getList($ids);
        $list = $this->wlPro($list);
        $list = $this->wlOrder($list);

        $excel = new PHPExcel();
        $excel->getProperties()
            ->setCreator("YangLiu")
            ->setLastModifiedBy("YangLiu")
            ->setTitle("销售订单")
            ->setSubject("Subject");
        $excel->getDefaultStyle()->getFont()->setName('Microsoft Yahei');
        $excel->getDefaultStyle()->getFont()->setSize(12);

        $this->sharedStyle = new PHPExcel_Style();
        $this->sharedStyle->applyFromArray(
            array(
                'fill'      => array(
                    'type'  => PHPExcel_Style_Fill::FILL_SOLID,
                    'color' => array('rgb' => '000000')
                ),
                'font'      => array(
                    'color' => array('rgb' => "000000"),
                ),
                'alignment' => array(
                    'vertical'   => PHPExcel_Style_Alignment::VERTICAL_CENTER,
                    'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
                    'indent'     => 1
                ),
                'borders'   => array(
                    'allborders' => array('style' => PHPExcel_Style_Border::BORDER_THIN),
                )
            ));

        try {
            $worksheet = $excel->setActiveSheetIndex(0);
        } catch (\PHPExcel_Exception $e) {

        }

        $worksheet->setTitle('物流导出');

        $worksheet->setCellValue('A1', '订单号*');
        $worksheet->setCellValue('B1', '重量');
        $worksheet->setCellValue('C1', '商品信息');
        $worksheet->setCellValue('D1', '备注');
        $worksheet->setCellValue('E1', '发件人姓名*');
        $worksheet->setCellValue('F1', '代理商名称');
        $worksheet->setCellValue('G1', '发件人手机*');
        $worksheet->setCellValue('H1', '发件人省市区');
        $worksheet->setCellValue('I1', '发件人详细地址*');
        $worksheet->setCellValue('J1', '发件人邮编');
        $worksheet->setCellValue('K1', '销售订单号');
        $worksheet->setCellValue('L1', '自定义区域1');
        $worksheet->setCellValue('M1', '收件人姓名*');
        $worksheet->setCellValue('N1', '收件人电话');
        $worksheet->setCellValue('O1', '收件人手机*');
        $worksheet->setCellValue('P1', '收件人省市区');
        $worksheet->setCellValue('Q1', '收件人详细地址*');
        $worksheet->setCellValue('R1', '单号');
        $worksheet->setCellValue('S1', 'A学习书');
        $worksheet->setCellValue('T1', 'B练习书');
        $worksheet->setCellValue('U1', 'C素材书');
        $worksheet->setCellValue('V1', '字词句手册');
        $worksheet->setCellValue('W1', '年级阅读');
        $worksheet->setCellValue('X1', '教案');
        $worksheet->setCellValue('Y1', '数学');
        $worksheet->setCellValue('Z1', '备注');
        $worksheet->setCellValue('AA1', '缺货');
        $worksheet->setCellValue('AB1', '补货');
        $worksheet->setCellValue('AC1', '短信1=自动发送2=手动发送');
        //去除所有空格
        array_walk($list,function (&$value,$k) use ($worksheet,$excel){
            $value['goods_name'] = '';
            if($value['status'] == 1)
            {
                $data = collection($this->modelOrderInfo->where('order_sn','in',$value['order_sn'])->field('goods_name,sum(num) as nums,dk')->group('wxproduct_id')->select())->toArray();
                array_walk($data,function ($data,$key) use(&$value){
                    if($data['dk'])
                    {
                        $data['dk'] = "({$data['dk']})";
                        return $value['goods_name'] .= $data['goods_name'].=$data['dk'] .='['.$data['nums']."]\r\n";
                    }
                    return $value['goods_name'] .= $data['goods_name'] .='['.$data['nums']."]\r\n";
                });
            }
            if($value['status'] == 2)
            {
                array_walk($value['pro'],function ($data,$key) use(&$value){
                    return $value['goods_name'] .= $data['name'] .="[".$data['num']."]\r\n";
                });
            }

            unset($value['pro']);
            $Key = $k+2;
            $worksheet->setCellValue("E".$Key,'宏达一甲'.$value['agent_id']);//发件人姓名*
            $worksheet->setCellValue("F".$Key, $value['agent_name']);//代理商名称
            $worksheet->setCellValue("G".$Key, '01088872966');//发件人手机*
            $worksheet->setCellValue("I".$Key, '北京市海淀区西土城路13号');//发件人详细地址*
            $worksheet->setCellValue("K".$Key, $value['order_sn'].',');//销售订单号*
            $worksheet->setCellValue("L".$Key, $value['goods_name']);//自定义区域1
            $worksheet->setCellValue("M".$Key, $value['name']);//收件人姓名*
            $worksheet->setCellValue("O".$Key, trim($value['phone']));//收件人手机*
            $address = str_replace(' ', '', $value['address']);
            $worksheet->setCellValue("Q".$Key, $address);//收货人地址
            $worksheet->setCellValue("AC".$Key, 1);//短信1=自动发送2=手动发送
            $worksheet = $excel->getActiveSheet();
            $worksheet->getColumnDimension('A')->setWidth(10); //设置列宽
            $worksheet->getColumnDimension('B')->setWidth(20);
            $worksheet->getColumnDimension('C')->setWidth(20);
            $worksheet->getColumnDimension('D')->setWidth(10);
            $worksheet->getColumnDimension('E')->setWidth(20);
            $worksheet->getColumnDimension('F')->setWidth(15);
            $worksheet->getColumnDimension('G')->setWidth(25);
            $worksheet->getColumnDimension('H')->setWidth(20);
            $worksheet->getColumnDimension('I')->setWidth(20);
            $worksheet->getColumnDimension('J')->setWidth(20);
            $worksheet->getColumnDimension('K')->setWidth(15);
            $worksheet->getColumnDimension('L')->setWidth(45);
            $worksheet->getColumnDimension('M')->setWidth(15);
            $worksheet->getColumnDimension('N')->setWidth(15);
            $worksheet->getColumnDimension('Q')->setWidth(50);
            $worksheet->getColumnDimension('AC')->setWidth(20);
            $worksheet->getRowDimension($Key)->setRowHeight(17); //设置行高
        });
        try {
            $excel->createSheet();
        } catch (\PHPExcel_Exception $e) {

        }
        // Redirect output to a client’s web browser (Excel2007)
        $title = '物流导出'.date("YmdHis");
        $endtime = date('Y-m-d H:i:s',time());
        if(count(explode(',',$ids)) == 1)
        {
            $row = $this->model->get($ids);
            $row->wl += 1;
            $row->save();
            $agentName = Info::getName($row->agent_id);
            $title = '物流-'.$agentName.'-'.$row->id.'-'.date('Y-m-d').'-导出次数'.$row->wl;
            \app\admin\model\Wxorder::msg([
                'moban'=>'wldc',
                'num'=>$row->wl,
                'id'=>$row->id,
                'createtime'=>$createtime,
                'endtime'=>$endtime,
                'name'=>$this->auth->username
            ]);
            $row->save();
        }else{
            foreach (explode(',',$ids) as $value)
            {
                $row1 = $this->model->get($value);
                $row1->wl += 1;
                $row1->save();
                \app\admin\model\Wxorder::msg([
                    'moban'=>'wldc',
                    'num'=>$row1->wl,
                    'id'=>$row1->id,
                    'createtime'=>$createtime,
                    'endtime'=>$endtime,
                    'name'=>$this->auth->username
                ]);
            }
        }

        unset($createtime,$endtime);

        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $title . '.xlsx"');
        header('Cache-Control: max-age=0');
        // If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');
        // If you're serving to IE over SSL, then the following may be needed
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0
        $objWriter = PHPExcel_IOFactory::createWriter($excel, 'Excel2007');
        try {
            $objWriter->save('php://output');
        } catch (\PHPExcel_Writer_Exception $e) {

        }
        return;
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $count = $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();
            $count = 0;
            foreach ($list as $k => $v) {
                $list2 = $this->modelOrder->where('id','in',$v->order_ids)->select();
                foreach ($list2 as $item)
                {
                    $this->modelOrderInfo->where('order_sn','in',$item->order_sn)->delete();
                    $item->delete();
                }

                $count += $v->delete();
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

}
